package com.example.service;

import java.util.List;

import javax.persistence.NoResultException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.example.bean.OrderCondition;
import com.example.model.Order;
import com.example.model.OrderItem;
import com.example.repository.OrderRepository;

@Service
public class OrderService {

    @Autowired
    OrderRepository orderRepository;

    public Page<Order> findOrderPage(OrderCondition orderCondition, Pageable pageable) {
        Page<Order> result = orderRepository.findByCriteria(orderCondition, pageable);
        if (result == null) {
            throw new NoResultException("The result set is not exits.");
        }
        return result;
    }

    public List<Order> findOrderAll() {
        return orderRepository.findAll();
    }

    public Order createOrder(Order creatingOrder) {

        String orderNum = creatingOrder.getOrderNum();
        Long count = orderRepository.countByOrderNum(orderNum);
        if (count != 0) {
            throw new DuplicateKeyException(
                    String.format("The order has been exist in database. [orderNum=%s]", orderNum));
        }

        // 计算订单金额
        double money = 0;
        for (OrderItem item : creatingOrder.getOrderItems()) {
            money += item.getBuyNum() * item.getProduct().getPrice();
        }
        creatingOrder.setMoney(money);

        return orderRepository.save(creatingOrder);
    }

    public Order updateOrder(String orderNum, Order updatingOrder) {
        Order order = orderRepository.findByOrderNum(orderNum);
        if (updatingOrder.getRecivePhone() != null) {
            order.setRecivePhone(updatingOrder.getRecivePhone());
        }
        return order;
    }

    public void deleteOrder(String orderNum) {
        orderRepository.delete(orderNum);
    }



}
